var Person = require("./../cors/models/person");
var Q = require('q');
var configVar = require("../config/code");
var dbPerson = {};

//添加
dbPerson.add = function (option) {
    var deferred = Q.defer();
    option = option || {};
    var parent = option.parent || -1;

    if(option.born){
        option.bornT = new Date(option.born).getTime();
    }

    
    var  person = new Person(option);
    if(parent == -1){
        person.save( (err, user) => {
            if (err) {
                deferred.reject(configVar.dbSave);
                global.logger.error("数据库操作错误:",err);
            }else{
                deferred.resolve(configVar.success);
            }
        });
    }else{
        //先查询该父亲是否存在
        Person.findById(parent,function (err,res) {
            if(err){
                deferred.reject(configVar.dbSave);
                global.logger.error("数据库操作错误:",err);
            }else if(!res){

                deferred.reject(configVar.invalid);
                global.logger.error("无效的父id:",parent);
            }else{
                person.save( (err, user) => {
                    if (err) {
                        deferred.reject(configVar.dbSave);
                        global.logger.error("数据库操作错误:",err);
                    }else{
                        user = JSON.parse(JSON.stringify(user));
                        dbPerson.addChild({
                            parent:option.parent,
                            id:user._id,
                            name:option.name
                        }).then(function (ret) {
                            deferred.resolve(ret);
                        }).catch(function (ret) {
                            deferred.reject(ret);
                        });
                    }
                });
            }
        });
}
    return deferred.promise;
};

dbPerson.update = function (option) {
    var deferred = Q.defer();
    option = option || {};
    if(option.born){
        option.bornT = new Date(option.born).getTime();
    }
    Person.update({_id:option._id},option ,function (err,res) {
        if(err){
            deferred.reject(configVar.dbSave);
            global.logger.error("数据库操作错误:",err);
        }else{
            deferred.resolve(configVar.success);
        }
    });
    return deferred.promise;
}

dbPerson.addChild = function (option) {
    var deferred = Q.defer();
    option = option || {};
    var id = option.parent;
    Person.update({"_id":id},{$push:{child:option.id}},(err,result)=>{
        if(err){
            deferred.reject(configVar.dbUpdate);
            global.logger.error("数据库操作错误:",err);
        }else{
            deferred.resolve(configVar.success);
        }
    })
    return deferred.promise;
}

//查找root
dbPerson.getRoot = function () {
    var deferred = Q.defer();
    var ret = {};
    Person.find({parent:"-1"},{desc:0}).sort({"order": 1}).exec(function (err,result) {
        if(err){
            deferred.reject(configVar.dbFind);
            global.logger.error("数据库操作错误:",err);
        }else if(!result){
            ret.data = [];
            Object.assign(ret , configVar.success);
            deferred.resolve(ret);
        }else{
            ret.data = result;
            Object.assign(ret , configVar.success);
            deferred.resolve(ret);
        }
    });
    return deferred.promise;
}

//查找详细信息
dbPerson.findDetailById = function (option) {
    var deferred = Q.defer();
    option = option || {};
    var id = option.id || '';
    if(!id){
        process.nextTick(function(){
            deferred.reject(configVar.invalid);
            global.logger.error("无效的父id:",id);
        });
        return deferred.promise;
    }
    Person.findById(id,function (err,res) {
        if(err){
            deferred.reject(configVar.dbFind);
            global.logger.error("数据库操作错误:",err);
        }else if(!res){
            deferred.reject(configVar.invalid);
            global.logger.error("无效的父id:",id);
        }else if(res.parent && res.parent != -1){
            Person.findOne({_id:res.parent},{name:1},function (err,result) {
                if(err){
                    deferred.reject(configVar.dbFind);
                    global.logger.error("数据库操作错误:",err);
                }else if(!result ){
                    deferred.reject(configVar.invalid);
                    global.logger.error("无效的父id:",res.parent);
                }else{
                    console.log(result);
                    res.parentNm = result.name;
                    var ret = {data:res};
                    Object.assign(ret , configVar.success);
                    deferred.resolve(ret);
                }
            });

        }else{
            res.parentNm = '';
            var ret = {data:res};
            Object.assign(ret , configVar.success);
            deferred.resolve(ret);
        }
    });


    return deferred.promise;
}

//根据自己的id找，子节点
dbPerson.getChildBySelfId = function (option) {
    var deferred = Q.defer();
    option = option || {};
    var id = option.id || -1;
    var ret = {};

    if(!id){
        process.nextTick(function(){
            deferred.reject(configVar.invalid);
            global.logger.error("无效的父id:",id);
        });
        return deferred.promise;
    }

        Person.findById(id,function (err,res) {
            if(err){
                deferred.reject(configVar.dbFind);
                global.logger.error("数据库操作错误:",err);
            }else if(!res){
                deferred.reject(configVar.invalid);
                global.logger.error("无效的父id:",id);
            }else{
                var child = res.child || [];
                if(child.length > 0){
                    dbPerson.getById({ids:child}).then(function (ret) {
                        deferred.resolve(ret);
                    }).catch(function (ret) {
                        deferred.resolve(ret);
                    });
                }else{
                    ret.data = [];
                    Object.assign(ret , configVar.success);
                    deferred.resolve(ret);
                }

            }
        });



    return deferred.promise;
}

//根据节点找自己
dbPerson.getById = function (option) {
    var deferred = Q.defer();
    var ids = option.ids || [];
    if(ids.length == 0){
        process.nextTick(function(){
            deferred.reject(configVar.invalid);
            global.logger.error("无效的父id:",ids);
        });
        return deferred.promise;
    }
    
    Person.find({"_id":{"$in":ids}},{desc:0}).sort({"order": 1}).exec(function (err,result) {
        if(err){
            deferred.reject(configVar.dbFind);
            global.logger.error("数据库操作错误:",err);
        }else if(!result){
            deferred.reject(configVar.invalid);
            global.logger.error("无效的父id:",ids);
        }else {
            var ret = {data:result};
            Object.assign(ret , configVar.success);
            deferred.resolve(ret);
        }
    });

    return deferred.promise;
}

//改变父节点
dbPerson.changeParent = function (options) {
    var deferred = Q.defer();
    var _id = options._id;
    var old = options.old || -1;
    var parent = options.parent || -1;
    if(!_id){
        process.nextTick(function(){
            deferred.reject(configVar.invalid);
            global.logger.error("无效的父id:",_id);
        });
        return deferred.promise;
    }

    Person.update({_id:_id},{parent:parent}).then(function (ret) {
        if(old == -1 && parent == -1){
            deferred.reject(configVar.success);

        }else if(parent == -1 && old != -1){

            Person.update({_id:old},{$pull:{'child':_id}},function (err,ret) {
                    if(err){
                        deferred.reject(configVar.dbUpdate);
                        global.logger.error("数据库操作错误:",err);
                    }else {
                        deferred.reject(configVar.success);
                    }
            });
        }else if(old != -1 && parent != -1 ){

            Person.update({_id:old},{$pull:{'child':_id}},function (err,ret) {

                if(err){
                    deferred.reject(configVar.dbUpdate);
                    global.logger.error("数据库操作错误:",err);
                }else{
                    dbPerson.addChild({id:_id,parent:parent}).then(function (ret) {
                        deferred.resolve(ret);
                    }).catch(function (ret) {
                        deferred.reject(ret);
                    });
                }
            });
        }else if(old == -1 && parent != -1){
            dbPerson.addChild({id:_id,parent:parent}).then(function (ret) {
                deferred.resolve(ret);
            }).catch(function (ret) {
                deferred.reject(ret);
            });
        }
    }).catch(function (ret) {
        deferred.reject(ret);
    })


    return deferred.promise;
}

//删除自己
dbPerson.remove = function (option) {
    var deferred = Q.defer();
    var parent = option.parent || -1;
    var childs = option.child ;

    var _id = option._id || '';
    if(!_id){
        process.nextTick(function(){
            deferred.reject(configVar.invalid);
            global.logger.error("无效的id:",_id);
        });
        return deferred.promise;
    }
    
    Person.remove({_id:_id},function (err,ret) {
        if(err){
            deferred.reject(configVar.dbRemove);
            global.logger.error("数据库操作错误:",err);
        }else {
            if(parent != -1){
                Person.update({_id:parent},{$pull:{'child':_id}},function (err,ret) {
                    if(err){
                        deferred.reject(configVar.dbUpdate);
                        global.logger.error("数据库操作错误:",err);
                    }else if(childs.length > 0){
                        upchild();
                    }else{
                        deferred.resolve(configVar.success);
                    }
                });
            }else if(childs.length > 0){
                upchild();
            }else{
                deferred.resolve(configVar.success);
            }
        }
    });
    
    function upchild() {
        Person.update({"_id":{"$in":childs}},{"parent":"-1"},function (err,ret) {
            if(err){
                deferred.reject(configVar.dbRemove);
                global.logger.error("数据库操作错误:",err);
            }else {
                deferred.resolve(configVar.success);
            }
        })
    }


    return deferred.promise;
}

module.exports = dbPerson;